package com.fishcoco.app.yunhang.utils.retrofit;

import android.content.Context;
import android.text.TextUtils;

import com.fishcoco.app.yunhang.utils.constant.ConstantUtil;
import com.fishcoco.app.yunhang.utils.retrofit.api.ApiService;
import com.fishcoco.app.yunhang.utils.retrofit.converter.StringConverterFactory;
import com.fishcoco.app.yunhang.utils.retrofit.interceptor.BaseInterceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;


/**
 * Created by Lain on 2016/10/25.
 * retrofit2.0 工具类
 */

public class RetrofitClient {

    private static final int DEFAULT_TIMEOUT = 5;

    private ApiService apiService;

    private OkHttpClient okHttpClient;

    public static String baseUrl = ConstantUtil.API_BASE_URL;

    private static Context mContext;

    private static RetrofitClient sNewInstance;
    private static class SingletonHolder {
        private static RetrofitClient INSTANCE = new RetrofitClient(
                mContext);
    }
    public static RetrofitClient getInstance(Context context) {
        if (context != null) {
            mContext = context;
        }
        return SingletonHolder.INSTANCE;
    }


    public static RetrofitClient getInstance(Context context, String url) {
        if (context != null) {
            mContext = context;
        }
        sNewInstance = new RetrofitClient(context, url);
        return sNewInstance;
    }

    private RetrofitClient(Context context) {

        this(context, null);
    }

    private RetrofitClient(Context context, String url) {

        if (TextUtils.isEmpty(url)) {
            url = baseUrl;
        }
        Map<String, String> headers=new HashMap<>();
        if (ConstantUtil.GET_ACCESS_TOKEN!=null)
        {
            headers.put("token",ConstantUtil.GET_ACCESS_TOKEN);
        }
        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(
                        new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
                .addInterceptor(new BaseInterceptor(headers))
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(StringConverterFactory.create())
                .baseUrl(url)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public <S> ApiService createServiceReturnString() {
        return apiService;
    }

}
